<?php // $Id
/**
 * @file
 * Contains common functions used by kgallery modules
 */

if ( !function_exists ('mime_content_type') ){
   function fn_mime_content_type ( $f ){
       return trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
   }
}else{
    function fn_mime_content_type ($f){
       return mime_content_type($f) ;
   }
}


/**
 * Return a weight selection array
 */
function _select_weights($element) {
  for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
    $weights[$n] = $n;
  }
  $element['#options'] = $weights;
  $element['#type'] = 'select';
  return $element; 
}




function _load_all_files($excluded_vid){
  $files = $indrupal = array();
  $node = node_load(array('vid'=>$excluded_vid));
  if ($node->vid) {
    $result = db_query('SELECT * FROM {files} f INNER JOIN {upload} r ON f.fid = r.fid WHERE r.vid != %d AND f.fid NOT IN(%s) ORDER BY f.filename', $node->vid, empty($node->files)?'-1':join(array_keys($node->files), ","));
    while ($file = db_fetch_object($result)) {
      $files[t('In the Drupal filesystem')][$file->fid] = $file->filepath." - ".$file->filename ." ($file->filemime)\n";
      $indrupal[] = $file->filepath;
    }
  }
  foreach($node->files as $fid=>$file){
    $indrupal[] = $file->filepath;
  }
  
  $dir = (variable_get('file_directory_path', '.'));
  $sysfiles = file_scan_directory($dir, ".*$");
  
  foreach($sysfiles as $filepath=>$file){
    if(!in_array($filepath, $indrupal)){
      $files[t('On the filesystem only')][$filepath] = "$file->basename\n";
    }
  }
  return $files;
}


/**
 * checks filemimes
 * @return true
 */
function _xspf_playlist_filetype_supported($filetype) {
  $allowed = variable_get('xspf_filetype', 'flv,jpg,gif,png,mp3,swf');
  $allowed = explode(',', $allowed);
  foreach ($allowed as $type) {
    if ((trim($filetype)==$type)) { return true; }
  } 
}

/**
 *Generate a PNG from attached files node text
 */
function _kcreate_card($node){
    $fontpath = (variable_get('font_directory_path', '/usr/share/fonts/truetype/ttf-dejavu'));
    $filepath = (variable_get('file_directory_path', '.'));
    $filename = "";
    if(count($node->files)){
        foreach($node->files as $fid=>$file){
            if((substr($file->filemime, 0, 5)=='image') && file_exists($file->filepath)){
                    $filename = $file->filepath;
                    break; //Use first valid image file
            }
        }
    }
    
    $text = $node->body;
    $label = $_GET['lbl'];
    $matches = array();
    preg_match_all("/\<greeting(.*?)\/\>/", $text, $matches);
    (preg_match_all("#([a-z0-9]+)=['\"]?([^'\"\s]+)['\"]?#i", $text, $m));
    if(array_filter($m)) { # One of the subarrays contains at least 1 element
      $options = (array_combine($m[1], $m[2]));
    }
    $match = array();
    preg_match("/raw=['|\"]([[:alnum:]]*?)['|\"].*/", $matches[1][0], $match);
    $raw = trim($match[1], " \"'"); 
    $match = array();
    if(!empty($raw) && file_exists($filename) && ($label!='thumbnail')){//Simply read the file and output. Skip and resize if label=thumbnail
        header('Content-type: '.fn_mime_content_type($filename));
        header('Content-Transfer-Encoding: binary');
        header('Content-Disposition: inline; filename='.basename($filename));
        header('Content-Length: '.@filesize($filename));
        header("Expires: ".date("r", strtotime("next week")));	
        readfile($filename);
    }else{
        preg_match("/theme=['|\"]([[:alnum:]]*?)['|\"].*/", $matches[1][0], $match);
        $theme = trim($match[1], " \"'"); 
        $match = array();
        preg_match("/valign=['|\"]([[:alnum:]]*?)['|\"].*/", $matches[1][0], $match);
        $valignment = trim($match[1], " \"'"); 
        $match = array(); 
        preg_match("/halign=['|\"]([[:alnum:]]*?)['|\"].*/", $matches[1][0], $match);
        $alignment = trim($match[1], " \"'");  
        $match = array(); 
        preg_match("/font=['|\"]([[:alnum:]\.[:alnum:]]*?)['|\"].*/", $matches[1][0], $match);
        $font = trim($match[1], " \"'");  
        $text = trim(strip_tags($text));
        $text = ($text=="")?variable_get('site_name', 'kasahorow'):$text;	
        $lines = split("\n", $text);
        
        switch($label){
            case 'thumbnail':
	       $h = variable_get("kgreeting_thumb_h", 75);  
	       $w = variable_get("kgreeting_thumb_w", 100);
	       $fontsize = 6;
	       $innerborder = 1;
	       $outerborder = 1;
	       break;
            case 'preview':
            default:
	       $h = empty($options['height'])?
			variable_get('kgreeting_preview_h', 320) :
			$options['height'];
	       $w = empty($options['width'])?
			variable_get('kgreeting_preview_w', 520) :
			$options['width'];
	       $fontsize = empty($options['fontsize'])?
			      32 :
			      $options['fontsize'];
	       $innerborder = empty($options['innerborder']) ?
				 16 :
				 $options['innerborder'];
	       $outerborder = empty($options['outerborder']) ?
				 14 :
				 $options['outerborder'];
	       break;
        }
        
        if($font!="" && file_exists($fontpath."/".$font)){
                $fontfile=$fontpath."/".$font;
        }else{
                $fontfile=$fontpath."/".variable_get('kgreeting_default_font', "DejaVuSans.ttf");
        }
        
        //Create the image
        $im_template  =  imagecreatetruecolor ( $w,  $h );	
        $background = imagecolorallocate ( $im_template ,  255 , 255 ,  255 );//set the background to white
        
        if($filename){
                $im_file = imagecreatefromstring(file_get_contents("$filename"));
                list($width, $height) = getimagesize($filename);
        }else{
                $im_file = $im_template;
                $width = $w;
                $height = $h;
        }	
                
        $im = $im_template;
        if($w/2>$width && $h/2 > $height){//image is left as is
                $fw = ($width);
                $fh = ($height);
                $padding = $innerborder +1;
        }else{//resize to fit
                $fw = $w;
                $fh = $h;
                $padding=0;
        }
        imagefilledrectangle($im, 0, 0, $w, $h, imagecolorallocate ( $im ,  255 , 255 ,  255 ));
        imagecopyresized($im_template, $im_file, $padding, $padding, 0, 0, $fw, $fh, $width, $height);
        imagecolortransparent($im_template, $background);//make the white transparent
        header("Content-Type: image/png");
        header("Expires: ".date("r", strtotime("next week")));	
        
        switch($theme){
            case 'red':
            $borders = imagecolorallocate ( $im , 193, 202, 211 );
            $textcolor = imagecolorallocate ( $im ,  0xA5 , 0x5 ,  0 );
            break;
            case 'black':
            $borders = imagecolorallocate ( $im ,  255 , 255 ,  255 );
            $textcolor = imagecolorallocate ( $im ,  0 , 0 ,  0 );
            break;
            case 'white':
            $borders = imagecolorallocate ( $im ,  255 , 150 ,  0 );
            $textcolor = imagecolorallocate ( $im , 255 , 255 ,  255 );
            break;
            case 'blue':
            $textcolor = imagecolorallocate ( $im , 193, 202, 211 );
            $borders = imagecolorallocate ( $im , 193, 202, 211 );
            break;
            case 'adinkra':
            $textcolor = imagecolorallocate ( $im , 193, 202, 211 );
            $borders = imagecolorallocate ( $im , 193, 202, 211 );
            break;
            case 'simple': //no borders
            $textcolor = imagecolorallocate ( $im ,  0xA5 , 0x5 ,  0 );
            $borders = "none";
	    break;
	    case 'simplewhite': //no borders, white text
            $textcolor = imagecolorallocate ( $im ,  255 , 255 ,  255 );
            $borders = "none";
            break;
            default:
            $borders = imagecolorallocate ( $im ,  0 , 0 ,  0 );
            $textcolor = imagecolorallocate ( $im ,  255 , 255 ,  255 );
            break;
        }	
        imagefill($im, 0, 0, $background);
        if($borders!="none"){ 
                imagerectangle($im, $outerborder, $outerborder, $w-$outerborder, $h-$outerborder, $borders);
                imagerectangle($im, $innerborder, $innerborder, $w-$innerborder, $h-$innerborder, $borders);
        }
        
        //vertical alignment
        switch($alignment){
                case 'left':
                $offset = 2*$outerborder;
                $multiplier = 0;
                break;
                case 'center':
                $offset = $w/2;
                $multiplier = 0.5;
                break;
                case 'right':
                $offset = ($w - (2*$outerborder));
                $multiplier = 1;
                break;
                default:
                $offset = $w/2;
                $multiplier = 0.5;
                break;
        }
        //horizontal alignment
        $size = $fontsize/(1+count($lines)/$fontsize);
        $linespacing = 1.3;
        $Grand_Size = imagettfbbox($size, 0, $fontfile, $text);
        switch($valignment){
                case 'top'://write the message on the top,		
                for($i=0; $i < sizeof($lines); $i++){
                    $Text_Box_Size = imagettfbbox($size, 0, $fontfile, $lines[$i]);
                    $Text_Box_Width = abs($Text_Box_Size[2] + $Text_Box_Size[0]);
                    $Text_Box_Height = abs($Text_Box_Size[7] + $Text_Box_Size[1]) *$linespacing;
                    $Text_Height = ($Text_Height + $Text_Box_Height);
                    $posx = $offset - ($Text_Box_Width*$multiplier);
                    $posy = (2*$outerborder)  + $Text_Height ;
                        imagettftext ($im, $size, 0, $posx, $posy, $textcolor, $fontfile, $lines[$i]);
                }
                break;
                case 'middle'://write the message in the middle		
                for($i=0; $i < sizeof($lines); $i++){
                    $Text_Box_Size = imagettfbbox($size, 0, $fontfile, $lines[$i]);
                    $Text_Box_Width = abs($Text_Box_Size[2] + $Text_Box_Size[0]);
                    $Text_Box_Height = abs($Text_Box_Size[7] + $Text_Box_Size[1]) *$linespacing;
                    $Text_Height = $Text_Height + $Text_Box_Height;
                    $posx = $offset - ($Text_Box_Width*$multiplier) ;
                    $posy = ($h - (abs($Grand_Size[7]+$Grand_Size[1])-$Text_Height) ) -h/2 - abs($Grand_Size[7]+$Grand_Size[1])/2;
                        imagettftext ($im, $size, 0, $posx, $posy, $textcolor, $fontfile, $lines[$i]);
                }
                break;
                case 'bottom'://write the message on the top,		
                
                for($i=0; $i < sizeof($lines); $i++){
                    $Text_Box_Size = imagettfbbox($size, 0, $fontfile, $lines[$i]);
                    $Text_Box_Width = abs($Text_Box_Size[2] + $Text_Box_Size[0]);
                    $Text_Box_Height = abs($Text_Box_Size[7] + $Text_Box_Size[1]) *$linespacing;
                    $Text_Height = $Text_Height + $Text_Box_Height;
                    $posx = $offset - ($Text_Box_Width*$multiplier) ;
                    $posy = $h - (abs($Grand_Size[7]+$Grand_Size[1])-$Text_Height);
                        imagettftext ($im, $size, 0, $posx, $posy, $textcolor, $fontfile, $lines[$i]);
                }
                break;		
                default:
                $size=9;
                $fill = imagecolorallocate ( $im ,  251,  121, 34 );    
                $light = imagecolorallocate ( $im,  255,  255,  255 );    
                $corners = imagecolorallocate ( $im ,  153 , 153 ,  102 );    
                $dark = imagecolorallocate ( $im , 51, 51 , 0 );    
                $black = imagecolorallocate ( $im , 0, 0 , 0 );    
        
                $colors[1] = imagecolorallocate ( $im ,  255 , 255 ,  255 );    
                $colors[2] = imagecolorallocate ( $im ,  255*0.95 , 255*0.95 ,  255*0.95 );    
                $colors[3] = imagecolorallocate ( $im ,  255*0.9 , 255*0.9 ,  255*0.9 );    
                $colors[4] = imagecolorallocate ( $im ,  255*0.85 , 255*0.85 ,  255*0.85 );    
        
                
                
                srand($node->nid);
                $c=1;
                $anz=10;
                $step=4/$anz;
                for($i=0;$i<$anz;$i+=1)
                {
                        $size=rand(7,70);
                        $x=rand(-390,390);
                        $y=rand(-100,400);
                        $color=$colors[$c];
                        $c+=$step;
                        imagettftext ($im, $size, 0, $x, $y, $color, $fontfile, $text);
                }
        
                imageline ( $im , 0 ,0, $w-1, 0, $light );    
                imageline ( $im , 0 ,0, 0, $h-2, $light );    
                imageline ( $im , $w-1,0, $w-1, $h, $dark );    
                imageline ( $im , 0 ,$h-1, $w-1, $h-1, $dark );    
                imagesetpixel ( $im , 0 ,$h-1, $corners );    
                imagesetpixel ( $im , $w-1 ,0, $corners );
                break;    
        }
        
        imagepng ( $im );
        imagedestroy($im); //free memory
    }
}

//-----------------FILTERS----------------//
/**
 * kasahorow Greetings filter
 */
function _kgreeting_card($node, $attributes=array()){
    $options = array();
    
    if(!empty($attributes['size'])){
        $options = array('query'=> 'lbl='.$attributes['size']);
    }
    $img = '<img src="'. url("node/$node->nid/greeting", $options) .'" alt="'. check_plain($node->title) .'" title="'. check_plain($node->title) .'" '. drupal_attributes($attributes) .' />';
    if($attributes['teaser'] == 'thumbnail'){
        $img = l($img, "node/$node->nid", array('html'=>TRUE));
    }
    return $img;
}
/**
 * YouTube filter
 */
function googtube_youtube($match) {
  $parsed_url = parse_url(check_url($match[0]));
  parse_str($parsed_url['query'], $parsed_query);
  $youtube_id = $parsed_query['v'];
  return '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/' . $youtube_id . '"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' . $youtube_id . '" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
}

/**
 * Google Video filter
 */
function googtube_google($match) {
  $parsed_url = parse_url(check_url($match[0]));
  parse_str($parsed_url[query], $parsed_query);
  $googlevideo_id = $parsed_query['docid'];
  isset($parsed_query['hl']) ? $googlevideo_hl = '&hl=' . $parsed_query['hl'] : $googlevideo_hl = '';
  return '<embed style="width:400px; height:326px;" id="VideoPlayback" type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docId=' . $googlevideo_id . $googlevideo_hl . '" flashvars=""> </embed>';
}

/**
 * Returns the replacement text for the matching context links RE
 * provided.  Called as a callback from _contextlinks_process().
 *
 * @param $matches
 *   The array containing the matching subexpressions
 *   from the context links RE in _contextlinks_process().
 *
 * @return
 *   A string containing the replacement text appropriate
 *   for the provided matching subexpressions.
 */
function _contextlinks_callback($matches) { 
    $class = strtolower($matches[1]);
    switch ($matches[2]) {
      case '^':
        $rel = 'nw';
        break;
  
      case '`':
        $rel = '';
        break;
    }
    $url = url($matches[3]);
    $text = preg_replace('/\\\\(.)/', '$1', $matches[4]);
    
    $rel = (isset($rel) ? $rel : "");
    $markup = '<span class="contextlinks-text"><a href="{URL}"{TARGET}>{TEXT}</a></span>';
    return (str_replace(array('{URL}', '{TARGET}', '{TEXT}'), array($url, $rel, $text), $markup));
}

function _gallery_file_form($form, $fid){
    $form = array();
    $fields = split(',', variable_get('xspf_playlist_metadata', 'textarea#>caption#>Subtitle Captions'));
    $meta = db_result(db_query("SELECT meta FROM {kfiles} WHERE fid=%d", $fid));
    $form[$fid] = array(
			'#type'=>'fieldset',
			'#title' => t('File metadata'),
//			'#collapsible' => TRUE,
//                        '#collapsed' => FALSE,
			'#tree'=>TRUE,
			);
    $meta = is_string($meta)?unserialize($meta):''; 
    foreach($fields as $child) {
                    list(,$name,) = split('#>', $child);
		    $handler = _handlers($child, (isset($meta[$name])?$meta[$name]:''));
                    $form[$fid][$name] = $handler->form;
                    //$form['syn']['children'][$name] = array('#type'=>'textfield');
    }
    $form['fid'] = array('#type'=>'value', '#value'=>$fid);
    $form['submit'] = array('#type'=>'submit', '#value'=>t('Save'));
    return $form;
}

function _gallery_file_form_submit($state, $form){
    $values = $form['values'];
    db_query("REPLACE INTO {kfiles}(fid, meta) VALUES(%d, '%s')", $values['fid'], serialize($values[$values['fid']]));
}

/**
 *
 */

function _gallery_file($fid){ 
    $meta = db_result(db_query("SELECT meta FROM {kfiles} WHERE fid=%d", $fid));
    if(is_string($meta)){
        $meta = unserialize($meta);
    }
    
    if(isset($meta['captions'])){
        header("content-type:text/xml;charset=utf-8");
        print_r(($meta['captions']));
    }
}


function _gallery_recommendations($node){
    $output ="<recommendations>";
    foreach($node->relations as $type=>$link){
        foreach($link as $relation){
            $thumbnail = trim(theme('xspf_playlist_thumb_get', node_load($relation['nid'])));
            $output.="<recommendation><title>".strip_tags($relation[title])."</title><link>".url("node/$relation[nid]", array('absolute'=>TRUE))."</link><image>$thumbnail</image></recommendation>";
        }
    }
    $output.="</recommendations>";
    header("content-type:text/xml;charset=utf-8");
    print $output;
}

function _gallery_vars($node=NULL, $teaser=FALSE){
    $output ="<config>";
    $output.="<file>".url("node/$node->nid/files", array('absolute'=>TRUE))."</file>";
    $output.="<recommendations>".url("node/$node->nid/links", array('absolute'=>TRUE))."</recommendations>";
    $output.="<id>".$node->nid."</id>";
    foreach(variable_get('mplayer', array('height'=>300, 'width'=>350)) as $var=>$value){
        if($teaser && in_array($var, array('height', 'displayheight', 'width', 'displaywidth'))){
            
            $value = (strstr($var, 'height'))?variable_get("kgallery_thumb_height", 200):variable_get("kgallery_thumb_width", 200);
        }
if($var=='usefullscreen') { $var ='fullscreen'; }
        $output.="<$var>$value</$var>";
    }
    $output.="</config>";
    drupal_set_header('Content-Type: application/xml; charset=utf-8');
    print $output;
}

function _kgallery_node_load($vid) {
  $db = new KDatabase('kgallery_nodes');
  $rows = $db->RetrieveRows(array('wheres' => array("vid=$vid"), 'debug' => 0));
  return $rows;
}

function _kgallery_node_selection($vid) {
  $rows = _kgallery_node_load($vid);
  $media = array();
  foreach($rows as $r) {
    $media[$r->mid] = "$r->mid";
  }
  return $media;
}
